package handler

import (
	"context"
	"fmt"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/micro/go-micro/util/log"

	weather "weather/proto/weather"
)

type Weather struct{}

// Call is a single request handler called via client.Call or the generated client code
func (e *Weather) GetTomorrowWether(ctx context.Context, req *weather.Request, rsp *weather.Response) error {
	log.Log("Received Weather.GetTomorrowWether request")
	weatherRsp, err := http.Get("http://t.weather.sojson.com/api/weather/city/101200101")
	if err != nil {
		log.Info("获取天气信息出错")
	}
	defer func() {
		_ = weatherRsp.Body.Close()
	}()
	bodyC, _ := ioutil.ReadAll(weatherRsp.Body)
	weatherType := gjson.Get(string(bodyC), "data.forecast.1.type")
	windType := gjson.Get(string(bodyC), "data.forecast.1.fx")
	wind := gjson.Get(string(bodyC), "data.forecast.1.fl")
	minWeather := strings.Replace(gjson.Get(string(bodyC), "data.forecast.1.low").String(), "低温 ", "", -1)
	maxWeather := strings.Replace(gjson.Get(string(bodyC), "data.forecast.1.high").String(), "高温 ", "", -1)
	notice := gjson.Get(string(bodyC), "data.forecast.1.notice")

	rsp.Code = 200
	rsp.Msg = ""
	rsp.Data = fmt.Sprintf("【吴飞】明天，%s，%s%s，气温%s-%s；%s。", weatherType, windType, wind, minWeather, maxWeather, notice)
	return nil
}

func (e *Weather) GetToDayWether(ctx context.Context, req *weather.Request, rsp *weather.Response) error {
	log.Log("Received Weather.GetToDayWether request")
	rsp.Code = 200
	rsp.Msg = ""
	rsp.Data = "【吴飞】" + "今天白天，晴，北风3-4级，最高气温13℃；舒适度指数2级，人体感觉较舒适。"
	return nil
}
